home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 7: Sunsite / Linux Cubed Series 7 - Sunsite Vol 1.iso / system / news / inn1.000 / inn1.4sec-linux-src.tar / inn / lib / getopt.c < prev    next >
C/C++ Source or Header  |  1992-02-13  |  2KB  |  82 lines

  1. /*  $Revision: 1.1 $
  2. **
  3. */
  4. #include <stdio.h>
  5.  
  6. #define ERR(s, c)                    \
  7.     if (opterr) {                    \
  8.     char buff[2];                    \
  9.     buff[0] = c; buff[1] = '\n';            \
  10.     (void)write(2, av[0], strlen(av[0]));        \
  11.     (void)write(2, s, strlen(s));            \
  12.     (void)write(2, buff, 2);            \
  13.     }
  14.  
  15.  
  16. int    opterr = 1;
  17. int    optind = 1;
  18. int    optopt;
  19. char    *optarg;
  20.  
  21.  
  22. /*
  23. **  Return options and their values from the command line.
  24. **  This comes from the AT&T public-domain getopt published in mod.sources
  25. **  (i.e., comp.sources.unix before the great Usenet renaming).
  26. */
  27. int
  28. getopt(ac, av, opts)
  29.     int        ac;
  30.     char    *av[];
  31.     char    *opts;
  32. {
  33.     extern char    *strchr();
  34.     static int    i = 1;
  35.     char    *p;
  36.  
  37.     /* Move to next value from argv? */
  38.     if (i == 1) {
  39.     if (optind >= ac || av[optind][0] != '-' || av[optind][1] == '\0')
  40.         return EOF;
  41.     if (strcmp(av[optind], "--") == 0) {
  42.         optind++;
  43.         return EOF;
  44.     }
  45.     }
  46.  
  47.     /* Get next option character. */
  48.     if ((optopt = av[optind][i]) == ':'
  49.      || (p = strchr(opts,  optopt)) == NULL) {
  50.     ERR(": illegal option -- ", optopt);
  51.     if (av[optind][++i] == '\0') {
  52.         optind++;
  53.         i = 1;
  54.     }
  55.     return '?';
  56.     }
  57.  
  58.     /* Snarf argument? */
  59.     if (*++p == ':') {
  60.     if (av[optind][i + 1] != '\0')
  61.         optarg = &av[optind++][i + 1];
  62.     else {
  63.         if (++optind >= ac) {
  64.         ERR(": option requires an argument -- ", optopt);
  65.         i = 1;
  66.         return '?';
  67.         }
  68.         optarg = av[optind++];
  69.     }
  70.     i = 1;
  71.     }
  72.     else {
  73.     if (av[optind][++i] == '\0') {
  74.         i = 1;
  75.         optind++;
  76.     }
  77.     optarg = NULL;
  78.     }
  79.  
  80.     return optopt;
  81. }
  82.